<script lang="ts" setup>
import type { SystemRoleApi } from '#/api/core/user';
import type { UserRegistrationRequest } from '#/api/openapi/api';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { client } from '#/api/core/client';
import { $t } from '#/locales';

import { useCreateSchema, useEditSchema } from '../data';

const emits = defineEmits(['success']);

const adminuser = client.user;
const formData = ref<SystemRoleApi.SystemRole>();
const isCreate = ref(false);

const [Form, formApi] = useVbenForm({
  schema: useEditSchema(),
  showDefaultActions: false,
});
const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    if (id.value) {
      const payload = {
        displayName: values.name,
        email: values.remark,
        role: values.permissions,
      };
      try {
        await adminuser.updateUser(id.value, payload);
        await adminuser.toggleUserStatus(id.value);
        emits('success');
        drawerApi.close();
      } catch {
        drawerApi.unlock();
      }
    } else {
      const payload: UserRegistrationRequest = {
        username: values.username,
        email: values.email,
        password: values.password,
        displayName: values.name,
      };
      try {
        await adminuser.register(payload);
        emits('success');
        drawerApi.close();
      } catch {
        drawerApi.unlock();
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<SystemRoleApi.SystemRole>();
      formData.value = data;
      formApi.resetForm();
      if (data?.id) {
        isCreate.value = false;
        id.value = data.id;
        formApi.setState({ schema: useEditSchema() });
        formApi.setValues({
          ...data,
          permissions: data.permissions ?? [],
        });
      } else {
        isCreate.value = true;
        id.value = undefined;
        formApi.setState({ schema: useCreateSchema() });
        formApi.setValues({
          password: '123456',
        });
      }
    }
  },
});

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? $t('common.edit', $t('system.role.name'))
    : $t('common.create', $t('system.role.name'));
});
</script>
<template>
  <Drawer :title="getDrawerTitle">
    <Form />
  </Drawer>
</template>
<style lang="css" scoped>
:deep(.ant-tree-title) {
  .tree-actions {
    display: none;
    margin-left: 20px;
  }
}

:deep(.ant-tree-title:hover) {
  .tree-actions {
    display: flex;
    flex: auto;
    justify-content: flex-end;
    margin-left: 20px;
  }
}
</style>
